package com.oeandn.config;

import com.oeandn.common.ws.WebSocketSessionManager;
import com.oeandn.common.ws.WsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Slf4j
@Component
public class WebSocketServer extends AbstractWebSocketHandler {
    @Resource
    private WsService wsService;


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("客户端连接成功");
        // 客户端建立连接,将客户端的session对象加入到WebSocketSessionManager的sessionGroup中
        WebSocketSessionManager.add(session);
        //将连接结果返回给客户端
        wsService.sendMsg(session,session.getId()+" 连接成功"+ LocalDateTime.now().toString());
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("客户端关闭连接成功");
        // 关闭连接,从WebSocketSessionManager的sessionGroup中移除连接对象
        WebSocketSessionManager.removeAndClose(session);
    }


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("客户端发送："+message.getPayload());
        //将连接结果返回给客户端
        wsService.sendMsg(session,session.getId()+" 客户端发送【"+LocalDateTime.now().toString()+"】:"+ message.getPayload());
    }


    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        log.info("客户端二进制发送："+message.getPayload());
    }

    /**
     * 异常处理
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("socket 异常："+exception.getMessage(),exception);
        // 出现异常则关闭连接,从WebSocketSessionManager的sessionGroup中移除连接对象
        WebSocketSessionManager.removeAndClose(session);
    }
}

